import { Injectable } from '@angular/core';
import * as _ from 'lodash';
import * as moment from "moment";
import { FetchService } from '../../core/net/fetch.service';
import { isBoolean } from 'lodash';

const monthHead31 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];

const monthHead30 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];

@Injectable({
    providedIn: 'root'
})
export class DispatchPlanService {

    constructor(private fetchService: FetchService, ) {
    }

    /**
     * 根据日期计算 管理处月旬上报的模板类型
     * 9月-10月19号 冬灌 - 'winter'
     * 3、4、5月和 9月 旬上报 - 'tenDays'
     * 其他时间 月上报 - 'month'
     */
    getMngMonthReportType(date?): { title: string, type: string } {
        const day = date ? moment(date).valueOf() : moment().valueOf();
        const month = moment(day).month() + 1;
        const winterBegin = `${moment(day).year()}-08-31`;
        const winterEnd = `${moment(day).year()}-10-20`;
        if ((month > 2 && month < 6) || month === 8) {
            // return 'tenDays';
            return {
                title: `${month + 1}月`,
                type: 'tenDays'
            };
        } else if (moment(day).isAfter(winterBegin) && moment(day).isBefore(winterEnd)) {
            // return 'winter';
            return {
                title: '冬灌',
                type: 'winter'
            };
        } else {
            // return 'month';
            return {
                title: `${month + 1}月`,
                type: 'month'
            };
        }
    }

    getMonthDays(m, dataType = "", stDate = "10-12", enDate = "11-18"): Array<string> {
        let result = [];
        const xunHead = {
            'F': ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日'],
            'S': ['11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日'],
            'T': ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
        };
        const type = this.getMngReportTableType(m);
        if (m === '4' || m === '6') {
            xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];
        } else {
            xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];
        }
        if (m === '9') {
            result = monthHead30;
        } else if (['F', 'S', 'T'].includes(dataType)) {
            result = xunHead[dataType];
        } else if (m === 'd') {
            const stDateArr = stDate.split('-');
            const edDateArr = enDate.split('-');
            result = this.getMngWinterHead(stDateArr, edDateArr);
        } else {
            result = monthHead31;
        }

        return result;
    }

    getMngReportTableType(month: string): { type: string } {
        if (month === '4' || month === '5' || month === '6') {
            return { type: 'tenDays' };
        } else if (month === 'd' || month === 'D') {
            return { type: 'winter' };
        } else {
            return { type: 'month' };
        }
    }
    /**
     * 获取调度中心 冬灌行头
     */
    getCenterWinterRow(stDate: Array<string>, edDate: Array<string>): Array<string> {
        const start = [moment().year(), parseInt(stDate[0], 10) - 1, parseInt(stDate[1], 10)];
        const end = [moment().year(), parseInt(edDate[0], 10) - 1, parseInt(edDate[1], 10)];
        const row = [];
        const a = moment(end);
        const b = moment(start);
        const duration = a.diff(b, 'days');
        for (let i = 0; i <= duration; i++) {
            const date = moment(start).add(i, 'd').format('MM-DD');
            row.push(date);
        }
        return row;
    }
    /**
     * 根据流量数据计算水量
     * 公式：水量（万m³） = 流量（m³/s） * 8.64
     */
    getWaterByFlow(flow: number, day = 1): string {
        return this.keepTwoDecimalFull(flow * day * 8.64);
    }
    getWaterByFlowYi(flow: number, day = 1): string {
        return this.keepTwoDecimalFull(flow * day * 0.000864);
    }
    // 公式：水量（万m³）= 平均日流量 * 天数 *  0.000864
    getTotalWaterByFlow(averageFlow, days = 1) {
        return this.keepTwoDecimalFull(averageFlow * days * 0.000864);
    }
    // 强制补齐 小数位数
    keepTwoDecimalFull(x, num = 2): string {
        const f = Math.round(x * 100) / 100;
        let s = f.toFixed(num);
        let rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + num) {
            s += '0';
        }
        return s;
    }
    /**
     * 获取冬灌填报的表头数组
     */
    getMngWinterHead(stDate: Array<string>, edDate: Array<string>): Array<string> {
        const start = [moment().year(), parseInt(stDate[0], 10) - 1, parseInt(stDate[1], 10)];
        const end = [moment().year(), parseInt(edDate[0], 10) - 1, parseInt(edDate[1], 10)];
        const row = [];
        // const firstRow = [];
        // const secondRow = [];
        // const thirdRow = [];
        const a = moment(end);
        const b = moment(start);
        const duration = a.diff(b, 'days');
        for (let i = 0; i <= duration; i++) {
            const date = moment(start).add(i, 'd').format('MM月DD日');
            // if (i < 11) {
            //     firstRow.push(date);
            // } else if (10 < i && i < 21) {
            //     secondRow.push(date);
            // } else {
            //     thirdRow.push(date);
            // }
            row.push(date);
        }
        // return [firstRow, secondRow, thirdRow];
        return row;
    }
    getMngWinterThirdHead(stDate: Array<string>, edDate: Array<string>): Array<string> {
        const start = [moment().year(), parseInt(stDate[0], 10) - 1, parseInt(stDate[1], 10)];
        const end = [moment().year(), parseInt(edDate[0], 10) - 1, parseInt(edDate[1], 10)];
        const thirdRow = [];
        const a = moment(end);
        const b = moment(start);
        const duration = a.diff(b, 'days');
        for (let i = 0; i <= duration; i++) {
            const date = moment(start).add(i, 'd').format('MM月DD日');
            if (i > 30) {
                thirdRow.push(date);
            }
        }
        return thirdRow;
    }
    /**
     * 解析val开头的属性
     */
    getValList(obj, length?): Array<any> {

        const result = [];
        if (obj != undefined) {
            const keyArr = Object.keys(obj);
            keyArr.forEach(key => {
                //  key以val开头
                if (key.slice(0, 3) === 'val') {
                    result.push(obj[key]);
                }
            });
            return length ? result.slice(0, length) : result;
        }

    }

    //  合计列
    getColsTotal(data: Array<any>, rowNameList, intlObj: any = { areaId: 'feTotal', name: '合计' }): any {
        const totalObj = _.cloneDeep(intlObj);
        rowNameList.forEach(key => {
            const totalArr = data.map(item => {
                return parseFloat(item[key] || 0);
            });
            totalObj[key] = _.sum(totalArr);
        });
        return totalObj;
    }

    // 当前时间的 下一个 年月旬
    getNextDateInterval(): { y: string, m: string, dataType: string } {
        const xunRules = [4, 5, 6];
        const result = {
            y: "0",
            m: "0",
            dataType: null,
        };
        const day = moment().date();
        const month = moment().month() + 2;
        const year = moment().year();
        if (month == 1) {
            _.assign(result, {
                y: moment().add(1, 'M').year()
            });
        } else {
            _.assign(result, {
                y: moment().year()
            });
        }
        if (xunRules.includes(month)) {
            // 旬
            if (day >= 1 && day <= 10) {
                //  当前是上旬
                _.assign(result, {
                    m: moment().add(1, 'M').month(),
                    dataType: 'S'
                });
            } else if (day > 20) {
                //  当前是下旬
                _.assign(result, {
                    m: moment().add(2, 'M').month(),
                    dataType: 'F'
                });
            } else {
                //  中旬
                _.assign(result, {
                    m: moment().add(1, 'M').month(),
                    dataType: 'T'
                });
            }
        } else if (month === 10 || (month === 11)) {
            // 冬灌
            _.assign(result, {
                m: 'd',
                dataType: null
            });
        } else {
            // 月
            _.assign(result, {
                m: moment().add(2, 'M').month(),
                dataType: null
            });
        }
        result.m = result.m + "";
        result.y = result.y + "";
        return result;
    }

    roateArray(arr: Array<any>): Array<any> {
        const result = [];
        const arrLen = arr[0].length;
        for (let i = 0; i < arrLen; i++) {
            result.push([]);
        }
        arr.forEach((arrItem, i) => {
            arrItem.forEach((item, j) => {
                result[j].push(item);
            });
        });
        return result;
    }

    //   水利厅 求和 （除掉 大战场 固扩 红寺堡 水源泵站）
    sumSltData(list) {

        const listCache = list.filter((item, i) => {
            return ![12, 13, 14, 15].includes(i);
        });
        const sum = listCache.reduce((def, val) => {
            def += parseFloat(val || '0');
            return def;
        }, 0);
        return Math.ceil(sum);
    }

    //  处理接口返回数据格式 获取表格数据
    dataParse(dataList, valList): Array<any> {
        if (valList[0] !== null) {
            return dataList.map(item => {
                return _.filter(valList, o => {
                    return parseInt(o['areaId'], 10) === parseInt(item['areaId'], 10);
                });
            });
        }

        // return dataList.map(item => {
        //         return _.filter(valList, o => {
        //             return parseInt(o['areaId'], 10) === parseInt(item['areaId'], 10);
        //         });
        //     });


    }
    // 解析表格展示数据
    getTableDate(colNameList, valListOrignal, dataParams: { type: string, m: string, dataType: string, period: { st_date: string, ed_date: string } }): any {
        const type = dataParams.type;
        const m = dataParams.m;
        const dataType = dataParams.dataType;
        let valList = this.dataParse(colNameList, valListOrignal);
        console.log(valList);
        if (valList === undefined) {
            valList = [[], [], [], [], []];
        }
        const result = {
            tableList: [],
            keyList: [],
        };
        const period = dataParams.period;
        colNameList.forEach((item, index) => {
            const keyListRow = [];
            let row = [];
            const obj = {};
            if (type === 'tenDays') { // 旬
                // if (dataType === 'T') { // 下
                    if (dataType === 'T') { // 下
                        row = valList[index].length ? this.getValList(valList[index][0], 11) : new Array(11);

                    // row = valList[index].length ? this.getValList(valList[index][2], m === '5' ? 11 : 10) : new Array(m === '5' ? 11 : 10);
                } else {
                    row = valList[index].length ? this.getValList(valList[index][0], 10) : new Array(10);
                }
                // else if (dataType === 'S') {
                //     row = valList[index].length ? this.getValList(valList[index][1], 10) : new Array(10);

                // }
            } else if (type === 'winter') {
                const stDate = period['st_date'].split('-');
                const edDate = period['ed_date'].split('-');
                const tableHeader = this.getMngWinterHead(stDate, edDate);
                const row1 = valList[index].length ? this.getValList(valList[index][0], 10) : new Array(10);
                const row2 = valList[index].length ? this.getValList(valList[index][1], 10) : new Array(10);
                let row3 = [];
                let row4 = [];
                if (valList[index][3]) {
                    row3 = valList[index].length ? this.getValList(valList[index][2], 10) : new Array(10);
                    row4 = valList[index].length ? this.getValList(valList[index][3], tableHeader.length - 30) : new Array(tableHeader.length - 30);
                } else {
                    row3 = valList[index].length ? this.getValList(valList[index][2], tableHeader.length - 20) : new Array(tableHeader.length - 20);
                }
                row = [...row1, ...row2, ...row3, ...row4];
            } else {
                const monthLastLength = m === '9' ? 10 : 11;
                const row1 = valList[index].length ? this.getValList(valList[index][0], 10) : new Array(10);
                const row2 = valList[index].length ? this.getValList(valList[index][1], 10) : new Array(10);
                const row3 = valList[index].length ? this.getValList(valList[index][2], monthLastLength) : new Array(monthLastLength);
                row = [...row1, ...row2, ...row3];
            }

            for (let i = 0; i < row.length; i++) {
                const key = 'val' + i;
                keyListRow.push(key);
                obj[key] = row[i];
            }
            console.log(result);
            result.tableList.push(_.assign(_.cloneDeep(item), obj));
            result.keyList = keyListRow;
        });
        return result;
    }

    // 保存结果data处理
    getTableSubmitData(type, dataList): string {
        let result = "";
        if (type === 'tenDays') {
            // 旬
            const data = _.cloneDeep(dataList).map(item => {
                return {
                    areaId: item.areaId,
                    val: this.getValList(item)
                };
            });
            result = JSON.stringify(data);
        } else {
            // 月 & 冬灌
            const data = [];
            dataList.forEach(item => {
                const valList = this.getValList(item);
                const firstRow = [];
                const secondRow = [];
                const thirdRow = [];
                const fourthRow = [];
                valList.map((val, index) => {
                    if (index < 10) {
                        firstRow.push(val);
                    } else if (10 <= index && index < 20) {
                        secondRow.push(val);
                    } else if (20 <= index && type === 'month') {
                        thirdRow.push(val);
                    } else if (20 <= index && index < 30 && type === 'winter') {
                        thirdRow.push(val);
                    } else {
                        fourthRow.push(val);
                    }
                });
                const resultArr = [
                    {
                        areaId: item.areaId,
                        val: firstRow
                    },
                    {
                        areaId: item.areaId,
                        val: secondRow
                    },
                    {
                        areaId: item.areaId,
                        val: thirdRow
                    }
                ];
                if (type === 'winter') {
                    resultArr.push({
                        areaId: item.areaId,
                        val: fourthRow,
                    });
                }
                data.push(...resultArr);
            });
            result = JSON.stringify(data);
        }
        return result;
    }
    // 计划导出
    exportExcel(queryParams, targetFileName?, isGLC?): void {
        const params = {
            targetFileName: targetFileName, // 导出的文件名称（计划名称）
            queryParams: JSON.stringify(queryParams), // 详情的查询条件
            excelMapper: '',
        };
        const type = queryParams.reportId;
        if (type == 5 && isGLC) {
            if (queryParams.m === 'd') {
                params.excelMapper = `ExcelMapper-wrsReportData_${type}_d_${queryParams.manageId}`;
            } else {
                params.excelMapper = `ExcelMapper-wrsReportData_${type}_m_${queryParams.manageId}`;
            }
        } else {
            params.excelMapper = `ExcelMapper-wrsReportData_${type}`;
        }
        this.fetchService.export('comm/exceldb/exportExcel', params).subscribe(res => {
            const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
            const elink = document.createElement('a');
            elink.download = targetFileName + ".xlsx";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }
      // 计划导出YGDz增加
      exportExcelNew(paramsactive): void {
        // const params = {
        //     targetFileName: targetFileName, // 导出的文件名称（计划名称）
        //     queryParams: JSON.stringify(queryParams), // 详情的查询条件
        //     excelMapper: '',
        // };
        // const type = queryParams.reportId;
        // if (type == 5 && isGLC) {
        //     if (queryParams.m === 'd') {
        //         params.excelMapper = `ExcelMapper-wrsReportData_${type}_d_${queryParams.manageId}`;
        //     } else {
        //         params.excelMapper = `ExcelMapper-wrsReportData_${type}_m_${queryParams.manageId}`;
        //     }
        // } else {
        //     params.excelMapper = `ExcelMapper-wrsReportData_${type}`;
        // }
        this.fetchService.export('plan/wrsReportData/export', paramsactive).subscribe(res => {
            const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
            const elink = document.createElement('a');
            elink.download = paramsactive.targetFileName + ".xlsx";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }
    // 调度计划制定导出
    exportExcelActive(paramsactive): void {

        this.fetchService.export('plan/wrsReportData/exportTemplate', paramsactive).subscribe(res => {
            const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
            const elink = document.createElement('a');
            elink.download = paramsactive.targetFileName + ".xlsx";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    sum(list) {
        const sum = list.reduce((def, val) => {
            def += parseFloat(val || '0');
            return def;
        }, 0);
        return Math.ceil(sum * 100) / 100;
    }
    average(list) {
        return this.keepTwoDecimalFull(this.sum(list) / list.length);
    }
    // 判断是否是闰年
    isLeapyear(year) {
        return isBoolean(year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
    }
}
